package it.polimi.swKnights.SWIMv2.servlets.users;

import it.polimi.swKnights.SWIMv2.ejb.exceptions.InvalidLoginPrivilegesException;
import it.polimi.swKnights.SWIMv2.ejb.exceptions.LoginFailException;
import it.polimi.swKnights.SWIMv2.ejb.friendsEngine.FriendshipManagerRemote;
import it.polimi.swKnights.SWIMv2.servlets.SwimServlet;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class FriendsPageController
 */
public class FriendsPageController extends SwimServlet
{
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{
		String destination = "WEB-INF/friends/UserFriends.jsp";

		try
		{
			this.handleFriends(request);

		}
		catch (LoginFailException e)
		{
			this.handleError(request);
		}
		catch (InvalidLoginPrivilegesException e)
		{
			this.handleError(request);
		}
		request.getRequestDispatcher(destination).forward(request, response);
	}

	private void handleError(HttpServletRequest request)
	{
		request.setAttribute("error", "PROVA");
	}

	private void handleFriends(HttpServletRequest request)
			throws LoginFailException, InvalidLoginPrivilegesException
	{
		HttpSession session = request.getSession();
		String userName = (String) session.getAttribute("userName");
		String password = (String) session.getAttribute("password");
		FriendshipManagerRemote friendshipManager = this
				.lookUp(FriendshipManagerRemote.class);

		List<Map<String, String>> friends = friendshipManager.getFriendsList(userName, password);
		
		request.setAttribute("friends", friends);

	}

}
